import React, { useState, useEffect } from 'react';
import { Card, Input, Space, Select, message, Row, Col, Button } from 'antd';
import { SearchOutlined, FilterOutlined } from '@ant-design/icons';
import { getUnitMetrics, type UnitMetricsData } from '../../services/metrics';
import UnitListTable from './components/UnitListTable';

const { Option } = Select;

const UnitView: React.FC = () => {
    const [loading, setLoading] = useState(false);
    const [units, setUnits] = useState<UnitMetricsData[]>([]);
    const [searchText, setSearchText] = useState('');
    const [searchType, setSearchType] = useState<'all' | 'unitId' | 'appId'>('all');

    // 筛选条件
    const [activityFilter, setActivityFilter] = useState<string | undefined>(undefined);
    const [dataStatusFilters, setDataStatusFilters] = useState<string[]>([]);

    // 分页状态
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 20,
        total: 0,
    });

    // 排序状态
    const [sortField, setSortField] = useState<string>('');
    const [sortOrder, setSortOrder] = useState<'ascend' | 'descend' | undefined>(undefined);

    // 获取单元度量数据（后端分页）
    const fetchUnits = async () => {
        setLoading(true);
        try {
            const params: any = {
                current: pagination.current,
                size: pagination.pageSize,
            };

            // 搜索条件
            if (searchText.trim()) {
                if (searchType === 'unitId') {
                    params.unitId = searchText.trim();
                } else if (searchType === 'appId') {
                    params.appId = searchText.trim();
                } else {
                    params.keyword = searchText.trim();
                }
            }

            // 活跃度筛选
            if (activityFilter) {
                params.activityLevel = activityFilter;
            }

            // 数据状态筛选
            if (dataStatusFilters.length > 0) {
                params.dataStatus = dataStatusFilters.join(',');
            }

            // 排序参数
            if (sortField && sortOrder) {
                params.sortField = sortField;
                params.sortOrder = sortOrder === 'ascend' ? 'asc' : 'desc';
            }

            const response = await getUnitMetrics(params);

            if (response.code === 0) {
                const data = response.data;
                // 支持两种返回格式：分页格式和数组格式
                if (data && typeof data === 'object' && 'records' in data) {
                    // 分页格式
                    setUnits(data.records || []);
                    setPagination(prev => ({
                        ...prev,
                        current: data.current || 1,
                        total: data.total || 0,
                    }));
                } else {
                    // 数组格式（兼容旧接口）
                    const records = Array.isArray(data) ? data : [];
                    setUnits(records);
                    setPagination(prev => ({
                        ...prev,
                        total: records.length,
                    }));
                }
            } else {
                message.error(response.msg || '获取单元数据失败');
            }
        } catch (error) {
            console.error('获取单元数据失败:', error);
            message.error('获取单元数据失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchUnits();
    }, [pagination.current, pagination.pageSize, searchText, searchType, activityFilter, dataStatusFilters, sortField, sortOrder]);

    // 搜索类型变化（重置到第一页）
    const handleSearchTypeChange = (value: 'all' | 'unitId' | 'appId') => {
        setSearchType(value);
        setPagination(prev => ({ ...prev, current: 1 }));
    };

    // 活跃度筛选变化（重置到第一页）
    const handleActivityFilterChange = (value: string | undefined) => {
        setActivityFilter(value);
        setPagination(prev => ({ ...prev, current: 1 }));
    };

    // 数据状态筛选变化（重置到第一页）
    const handleDataStatusFilterChange = (checkedValues: string[]) => {
        setDataStatusFilters(checkedValues);
        setPagination(prev => ({ ...prev, current: 1 }));
    };

    // 清空所有筛选
    const handleClearAllFilters = () => {
        setSearchText('');
        setActivityFilter(undefined);
        setDataStatusFilters([]);
        setSortField('');
        setSortOrder(undefined);
        setPagination(prev => ({ ...prev, current: 1 }));
    };

    // 分页和排序变化处理
    const handleTableChange = (newPagination: any, _filters: any, sorter: any) => {
        // 处理分页变化
        setPagination(prev => ({
            ...prev,
            current: newPagination.current,
            pageSize: newPagination.pageSize,
        }));

        // 处理排序变化
        if (sorter.field) {
            setSortField(sorter.field);
            setSortOrder(sorter.order);
        } else {
            setSortField('');
            setSortOrder(undefined);
        }
    };

    return (
        <div style={{ padding: '24px 0' }}>
            <Card
                title="单元度量详情"
            >
                <Space direction="vertical" size="middle" style={{ width: '100%', marginBottom: '16px' }}>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Input
                                placeholder={
                                    searchType === 'unitId'
                                        ? '搜索单元ID'
                                        : searchType === 'appId'
                                            ? '搜索应用ID'
                                            : '搜索单元ID或应用ID'
                                }
                                prefix={<SearchOutlined />}
                                value={searchText}
                                onChange={(e) => setSearchText(e.target.value)}
                                allowClear
                                addonBefore={
                                    <Select
                                        value={searchType}
                                        onChange={handleSearchTypeChange}
                                        style={{ width: 90 }}
                                        variant="borderless"
                                    >
                                        <Option value="all">全部</Option>
                                        <Option value="unitId">单元ID</Option>
                                        <Option value="appId">应用ID</Option>
                                    </Select>
                                }
                            />
                        </Col>
                        <Col span={4}>
                            <Select
                                placeholder="仓库活跃度"
                                style={{ width: '100%' }}
                                value={activityFilter}
                                onChange={handleActivityFilterChange}
                                allowClear
                            >
                                <Option value="HIGH">高活跃</Option>
                                <Option value="MEDIUM">中活跃</Option>
                                <Option value="LOW">低活跃</Option>
                                <Option value="UNKNOWN">未知</Option>
                            </Select>
                        </Col>
                        <Col span={6}>
                            <Select
                                mode="multiple"
                                placeholder="数据就绪（选中必须可用）"
                                style={{ width: '100%' }}
                                value={dataStatusFilters}
                                onChange={handleDataStatusFilterChange}
                                maxTagCount="responsive"
                                allowClear
                            >
                                <Option value="jar">JAR</Option>
                                <Option value="git">GIT</Option>
                                <Option value="apm">APM</Option>
                                <Option value="sa">SA</Option>
                            </Select>
                        </Col>
                        <Col span={4}>
                            <Button
                                icon={<FilterOutlined />}
                                onClick={handleClearAllFilters}
                            >
                                重置筛选
                            </Button>
                        </Col>
                    </Row>
                </Space>

                <UnitListTable
                    units={units}
                    loading={loading}
                    showActions={false}
                    pagination={{
                        current: pagination.current,
                        pageSize: pagination.pageSize,
                        total: pagination.total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total: number, range: [number, number]) =>
                            `显示第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
                    }}
                    onChange={handleTableChange}
                    scroll={{
                        x: 1760,
                        y: 600 // 使用固定高度，确保分页器可见
                    }}
                />
            </Card>
        </div>
    );
};

export default UnitView;